import { IModelVersion, RenderMode } from '@bentley/imodeljs-common'
import {
  EventHandled,
  IModelApp,
  PrimitiveTool,
  RemoteBriefcaseConnection,
  ScreenViewport,
  TileAdmin,
  ViewTool
} from '@bentley/imodeljs-frontend'
import { OpenMode, Guid, ClientRequestContext } from '@bentley/bentleyjs-core'
import { IModelBankBasicAuthorizationClient } from '@bentley/imodelhub-client/lib/imodelbank/IModelBankBasicAuthorizationClient'
import { FrontendDevTools } from '@bentley/frontend-devtools'

import RpcHandle from "./rpc"

function configViewFlags () {
  const vf = IModelApp.viewManager.selectedView.viewFlags.clone()
  vf.visibleEdges = false
  vf.renderMode = Number.parseInt(RenderMode.SmoothShade, 10)
  IModelApp.viewManager.selectedView.viewFlags = vf
  IModelApp.viewManager.selectedView.synchWithView(false)
}

export class DisplayTestApp {
  static async initialize (opts) {
    if (IModelApp.initialized) {
      return
    }
    RpcHandle.init()
    opts = opts || {}
    opts.tileAdmin = TileAdmin.create({
      alwaysRequestEdges: false,
      alwaysSubdivideIncompleteTiles: false,
      cancelBackendTileRequests: true,
      enableExternalTextures: true,
      enableInstancing: true,
      retryInterval: 1000
    })

    const email = 'test'
    const password = 'test'
    opts.authorizationClient = new IModelBankBasicAuthorizationClient(
      { id: Guid.createValue() },
      { email, password }
    )

    opts.renderSys = {
      debugShaders: false,
      doIdleWork: true,
      dpiAwareLOD: false,
      dpiAwareViewports: true,
      filterMapDrapeTextures: true,
      filterMapTextures: false,
      logarithmicDepthBuffer: true,
      planProjections: true,
      preserveShaderSourceCode: false,
      useWebGL2: true
    }

    await IModelApp.startup(opts)

    await IModelApp.authorizationClient.signIn(new ClientRequestContext())

    IModelApp.renderSystem.enableDiagnostics(6) // RenderDiagnostics.ALL

    ViewTool.prototype.onResetButtonUp = function () {
      return EventHandled.Yes
    }
    PrimitiveTool.prototype.onResetButtonUp = function () {
      return EventHandled.Yes
    }
    return await FrontendDevTools.initialize()
  }

  static setActiveSnapModes (snaps) {
    IModelApp.accuSnap.setActiveSnapModes(snaps)
  }

  static setActiveSnapMode (snap) {
    this.setActiveSnapModes([snap])
  }

  static async openOnlineIModel (iModelId, versionId) {
    // Open the iModel
    return await RemoteBriefcaseConnection.open(
      '390e644d-37e4-4d5e-950c-4bcae05952ea',
      iModelId,
      OpenMode.Readonly,
      versionId
        ? IModelVersion.asOfChangeSet(versionId)
        : IModelVersion.latest()
    )
  }

  static async buildViewList (state) {
    try {
      const viewQueryParams = { wantPrivate: false }

      const viewSpecs = await state.views.getViewList(
        viewQueryParams
      )
      console.log('viewSpecsviewSpecs, ', viewSpecs)

      if (viewSpecs.length > 0) {
        let viewSpec
        viewSpecs.forEach(item => {
          if (item.name === 'Default' || item.name.toLowerCase() === 'default') {
            viewSpec = item.id
          } else {
            viewSpec = viewSpecs[0].id
          }
        })
        viewSpec = "0x30000001755"
        state.viewState = await state.views.load(viewSpec)
      }
      return viewSpecs
    } catch (e) {
      console.log(e)
    }
  }

  static async openView (state, domElmId) {
    // find the canvas.
    const parent = document.getElementById(domElmId)
    let viewSpecs
    if (parent) {
      try {
        viewSpecs = await DisplayTestApp.buildViewList(state)
      } catch (e) {
        console.log('openView err', e)
      }

      const vp = ScreenViewport.create(parent, state.viewState)
      IModelApp.viewManager.addViewport(vp)

      return { viewlist: viewSpecs, viewport: vp }
    }
  }
}

export { configViewFlags }

